package alipay

import (
	"github.com/gin-gonic/gin"
	"log"
	"time"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/logic"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/pkg/dingo"
	. "yundian/internel/pkg/dingo/result"
)

// ------------ 订单相关请求处理 ---------------//

// GetOrderList 获取订单列表
func GetOrderList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	openid, err := helper.GetUserNameFromCtx(ctx)
	if err != nil {
		Response(ctx)(err.Error(), CodeNeedLogin, nil)(Unauthorized)
		return
	}
	// 请求参数处理 -- 分页
	param := &request.OrderListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	log.Println("获取xcx_openId", openid)
	//userId := 51
	// 获取会员信息
	memberInfo := memberdao.NewMemberDao().GetMemberInfoById(userId).Unwrap().(*membermodel.MembersModel)
	param.MemberId = memberInfo.UUID
	//param.MemberId = userId
	//param.Openid = openid

	// 查询结果
	data := dao.NewOrderDao().AliPayOrdersList(param)
	// 分页信息
	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// GetAutoOrderList 获取订单列表
func GetAutoOrderList(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.AutoPayOrderListReq{}
	dingo.ErrorIf(ctx.ShouldBindQuery(param)).Unwrap()
	param.MemberId = userId

	data := dao.NewOrderAutoRenewDao().GetAutoRenewMonthlyOrderList(param)

	Response(ctx)("", CodeSuccess, ResponseList{
		PageNo:     param.PageNo,
		PageSize:   param.PageSize,
		TotalCount: data.Val().(int64),
		TotalPage:  (data.Val().(int64) + int64(param.PageSize) - 1) / int64(param.PageSize),
		Data:       data.Unwrap(),
	})(OK)
}

// GetOrderDetail 获取订单详情
func GetOrderDetail(ctx *gin.Context) {
	param := &struct {
		Id int `form:"id" binding:"required,gt=0"`
	}{}
	dingo.ErrorIf(ctx.Bind(param)).Unwrap()
	Response(ctx)("", CodeSuccess, dao.NewOrderDao().GetAliPayOrderDetail(param.Id).Unwrap())(OK)
}

// CloseTrade 关闭订单、结束订单
func HandleAliPayEndOrder(ctx *gin.Context) {
	userId, err := helper.GetUserIdFromCtx(ctx)
	dingo.ErrorIf(err).Unwrap()

	param := &request.CloseOrderReq{}
	log.Println("结束订单信息1：")
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.EndTime = time.Now().Unix()
	log.Println("结束订单信息2：", param)
	settResp := logic.NewOrderLogic().HandleZfbEndOrderV3(param, userId)

	Response(ctx)("", CodeSuccess, settResp)(OK)
}

func HandleAliPayEndOrderOld(ctx *gin.Context) {

	param := &request.CloseOrderReq{}
	log.Println("结束订单信息：==>")
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()
	param.EndTime = time.Now().Unix()
	log.Println("结束订单信息：=======>", param)
	settResp := logic.NewOrderLogic().HandleZfbEndOrder(param)

	Response(ctx)("", CodeSuccess, settResp)(OK)
}

func HandleCheckOrderStatus(ctx *gin.Context) {
	param := &struct {
		Openid   string `json:"openid"`
		DeviceSn string `json:"deviceSn"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	orderInfo := dao.NewOrderDao().GetOrderInfoByOpenidAndSn(param.Openid, param.DeviceSn).Unwrap().(*orders.OrderModel)

	Response(ctx)("", CodeSuccess, &struct {
		Id        int    `json:"id"` // 订单id
		Openid    string `json:"openid"`
		TradeNo   string `json:"tradeNo"`  // 订单编号
		DeviceSn  string `json:"deviceSn"` // 设备Sn
		State     int8   `json:"state"`    // 订单状态
		FeeMode   int8   `json:"feeMode"`  // 计费模式
		ProductId string `json:"productId"`
		PlaceName string `json:"placeName"`
		PayAt     int64  `json:"payAt"`
	}{
		Id:        orderInfo.Id,
		Openid:    orderInfo.Openid,
		TradeNo:   orderInfo.TradeNo,
		DeviceSn:  orderInfo.DeviceSn,
		State:     orderInfo.State,
		FeeMode:   orderInfo.FeeMode,
		ProductId: orderInfo.ProductId,
		PlaceName: orderInfo.PlaceName,
		PayAt:     int64(orderInfo.PayAt),
	})(OK)
}

func HandleCheckUserOrderStatus(ctx *gin.Context) {
	param := &struct {
		Openid string `json:"openid"`
	}{}
	dingo.ErrorIf(ctx.ShouldBindJSON(param)).Unwrap()

	orderInfo := dao.NewOrderDao().GetOrderInfoByOpenid(param.Openid).Unwrap().(*orders.OrderModel)

	Response(ctx)("", CodeSuccess, &struct {
		Id        int    `json:"id"` // 订单id
		Openid    string `json:"openid"`
		TradeNo   string `json:"tradeNo"`  // 订单编号
		DeviceSn  string `json:"deviceSn"` // 设备Sn
		State     int8   `json:"state"`    // 订单状态
		FeeMode   int8   `json:"feeMode"`  // 计费模式
		ProductId string `json:"productId"`
		PlaceName string `json:"placeName"`
		PayAt     int64  `json:"payAt"`
	}{
		Id:        orderInfo.Id,
		Openid:    orderInfo.Openid,
		TradeNo:   orderInfo.TradeNo,
		DeviceSn:  orderInfo.DeviceSn,
		State:     orderInfo.State,
		FeeMode:   orderInfo.FeeMode,
		ProductId: orderInfo.ProductId,
		PlaceName: orderInfo.PlaceName,
		PayAt:     int64(orderInfo.PayAt),
	})(OK)
}
